package evostar.service;

import evostar.dao.UserDAO;
import evostar.exception.ServerException;
import evostar.model.User;
import evostar.result.CodeMsg;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RedisService redisService;

    public static final String TOKEN_NAME = "token";
    public static final String TOKEN_PRE = "token_";

    public String login(HttpServletResponse response, String username, String password) {
        if (StringUtils.isEmpty(username)) {
            //username不能为空
            throw new ServerException(CodeMsg.ACCOUNT_EMPTY);
        }
        if (StringUtils.isEmpty(password)) {
            throw new ServerException(CodeMsg.PASSWORD_EMPTY);
        }
        User user = this.getByNmae(username);
        if (user == null) {
            throw new ServerException(CodeMsg.ACCOUNT_NOT_EXIST);
        }
        //验证密码
        if (!DigestUtils.md5Hex(password + user.getSalt()).equals(user.getPassword())) {
            throw new ServerException(CodeMsg.PASSWORD_ERROR);
        }
        //生成cookie
        String token = UUID.randomUUID().toString().replace("-", "");
        this.addCookie(response, token, user);
        return token;
    }

    public void addCookie(HttpServletResponse response, String token, User user) {
        int expire = 7 * 24 * 60 * 60;
        Cookie cookie = new Cookie(TOKEN_NAME, token);
        cookie.setPath("/");
        cookie.setMaxAge(expire);
        response.addCookie(cookie);
        redisService.setValue(TOKEN_PRE + token, user, expire);
    }

    public User getByNmae(String username) {
        return userDAO.getByName(username);
    }

    public User getByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisService.getValue(TOKEN_PRE + token, User.class);
        if (user != null) {
            addCookie(response, token, user);
            return user;
        }
        return null;
    }
}
